package com.rem.rabbitmq.ee.Gexchanges.direct;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rem.rabbitmq.ee.RabbitMqUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 交换机-直连模式
 * 将消息发送到绑定的routingkey的队列中去 没有绑定的消息会被丢弃
 *
 * @author Rem
 * @date 2021-12-24
 */

public class DirectExchangeProducer {


    public static void main(String[] args) throws Exception {

        Channel channel = RabbitMqUtils.getChannel();
        /**
         * 声明一个交换机
         * exchange: 交换机的名称
         * type:交换机的类型
         *
         */
        channel.exchangeDeclare(RabbitMqUtils.EXCHANGE_DIRECT, BuiltinExchangeType.DIRECT);

        System.err.println("开始发送消息...");
        Scanner scanner = new Scanner(System.in);


        /**
         * 创建多个bindingKey
         * 没有与routingKey绑定的消费者 消息发出后会丢失
         */
        Map<String, String> routingKeyMap = new HashMap<>();
        routingKeyMap.put("1", "green");
        routingKeyMap.put("2", "blue");
        routingKeyMap.put("3", "red");
        routingKeyMap.put("4", "pink");


        while (scanner.hasNext()) {
            String message = scanner.next();
            String routingKey;
            for (Map.Entry<String, String> entry : routingKeyMap.entrySet()) {
                String key = entry.getKey();
                if (message.equals(key)) {
                    routingKey = entry.getValue();
                    //发送消息
                    channel.basicPublish(RabbitMqUtils.EXCHANGE_DIRECT, routingKey, null, message.getBytes());
                    System.err.println("发送消息完毕" + message);
                }
            }
        }
    }


}
